package com.example.springbootvue.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT令牌提供者
 */
@Slf4j
@Component
public class JwtTokenProvider {

    @Value("${app.jwt.secret}")
    private String jwtSecret;

    @Value("${app.jwt.expiration}")
    private int jwtExpirationInMs;

    private SecretKey getSigningKey() {
        byte[] keyBytes = jwtSecret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 生成JWT令牌
     */
    public String generateToken(String username) {
        log.info("为用户生成JWT令牌: {}", username);

        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);

        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", username);
        claims.put("iat", now);
        claims.put("exp", expiryDate);

        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();

        log.info("JWT令牌生成成功");
        return token;
    }

    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        log.info("从令牌中获取用户名");

        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();

        String username = claims.getSubject();
        log.info("从令牌中获取到的用户名: {}", username);

        return username;
    }

    /**
     * 验证令牌
     */
    public boolean validateToken(String token) {
        try {
            log.info("验证JWT令牌");
            Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token);
            log.info("JWT令牌验证成功");
            return true;
        } catch (SignatureException ex) {
            log.error("无效的JWT签名");
            return false;
        } catch (MalformedJwtException ex) {
            log.error("无效的JWT令牌");
            return false;
        } catch (ExpiredJwtException ex) {
            log.error("过期的JWT令牌");
            return false;
        } catch (UnsupportedJwtException ex) {
            log.error("不支持的JWT令牌");
            return false;
        } catch (IllegalArgumentException ex) {
            log.error("JWT声明字符串为空");
            return false;
        }
    }
}